<template>
    <div class="payment-order-container">
        <el-row>
            <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
                <el-form :inline="true" :model="filter" class="demo-form-inline">
                    <el-form-item label="标题">
                        <el-input v-model="filter.title" placeholder="单据标题" clearable />
                    </el-form-item>
                    <el-form-item label="单据编号">
                        <el-input v-model="filter.id" placeholder="单据编号" clearable />
                    </el-form-item>
                    <el-form-item label="供应商">
                        <el-input v-model="filter.targetObjName" placeholder="供应商名称" clearable />
                    </el-form-item>

                    <el-form-item label="状态">
                        <el-select v-model="filter.status" placeholder="全部">
                            <el-option label="全部" value="" />
                            <el-option label="待审核" :value="CommonOrderStatus.WaitReview.code" />
                            <el-option label="已审核" :value="CommonOrderStatus.Passed.code" />
                        </el-select>
                    </el-form-item>

                    <el-form-item style="width: 300px" label="日期范围">
                        <el-date-picker v-model="dateRange" type="daterange" range-separator="~"
                            start-placeholder="开始日期" end-placeholder="结束日期" />
                    </el-form-item>

                    <el-form-item label="排序方式">
                        <el-select v-model="filter.sortType" placeholder="创建时间">
                            <el-option label="创建时间" :value="OrderSortType.CreateTime.code" />
                            <el-option label="业务时间" :value="OrderSortType.OperationTime.code" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
                <el-button icon="Plus" @click="createPaymentOrder()" type="primary">新建付款单</el-button>
                <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
                <el-table v-loading="loading" :data="dataList" style="width: 100%; min-width: 600px; height: 100%;"
                    @row-click="handleRowClick">
                    <el-table-column label="单据标题" align="center" prop="title" width="180" />
                    <el-table-column label="单据编号" align="center" prop="docCode" width="180" />

                    <el-table-column label="状态" align="center">
                        <template #default="scope">
                            <el-tag
                                :type="scope.row.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'">
                                {{ scope.row.status.name }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="供应商" align="center">
                        <template #default="scope">
                            {{ scope.row.targetObject?.name }}
                        </template>
                    </el-table-column>

                    <el-table-column label="付款日期" align="center">
                        <template #default="scope">
                            {{ formatDate(scope.row.operateDate) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="付款金额" align="center">
                        <template #default="scope">
                            {{ formatCurrency(scope.row.actualPayMount) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="200" align="center">
                        <template #default="scope">
                            <el-link :underline="false" type="primary" @click.stop="showDetail(scope.row)">
                                详情
                            </el-link>
                            <el-link v-if="scope.row.status.code === CommonOrderStatus.WaitReview.code"
                                :underline="false" type="danger" style="margin-left: 12px;"
                                @click.stop="reviewPaymentOrder(scope.row)">
                                审核
                            </el-link>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>

        <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
    </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { CommonOrderStatus, OrderSortType } from '../../public/engine/common/docDefinition'
import { DataPage } from '../../public/network/communicationConverter'
import { FundOrderFilter } from '../../public/engine/funds/paymentOrder'
import { DateUtil } from '../../public/utils/dateUtil'
import EventBus from '../../public/engine/ipc/eventBus'
import { deletePaymentOrderNetworkCacheData } from '../../public/network/api'
import { Util } from '../../public/utils/util'
import { uiNavigation } from '../../public/views/uiEntrance/uiNavigation'

export default {
    name: 'payment',

    data() {
        return {
            loading: false,
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 20,
            },
            filter: new FundOrderFilter(),
            dateRange: [],
            dataList: [],
            fundUiAction: new FundUiAction(),
            CommonOrderStatus,
            OrderSortType
        }
    },

    mounted() {
        this.getList()
        EventBus.on('paymentOrderUpdated', this.getList)
    },

    beforeUnmount() {
        EventBus.off('paymentOrderUpdated', this.getList)
    },

    methods: {
        async getList() {
            try {
                this.loading = true

                // Update filter with date range
                if (this.dateRange?.length === 2) {
                    this.filter.startDate = this.dateRange[0];
                    this.filter.endDate = new Date(this.dateRange[1])
                    this.filter.endDate.setHours(23, 59, 59, 999)
                } else {
                    this.filter.startDate = null
                    this.filter.endDate = null
                }

                const res = await this.fundUiAction.getPaymentOrderData({
                    pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
                    filter: this.filter.toJson({ withState: true })
                })

                if (res?.data?.dataList) {
                    this.dataList = res.data.dataList
                    this.total = res.data.pageInfo?.total || res.data.dataList.length
                } else if (res?.resErr) {
                    ElMessage.error('获取付款单列表失败: ' + res.resErr)
                }
            } catch (error) {
                console.error('获取付款单列表失败', error)
                ElMessage.error('获取付款单列表失败')
            } finally {
                this.loading = false
            }
        },

        handleSearch() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetSearch() {
            this.filter.clear()
            this.dateRange = []
            this.queryParams.pageNum = 1
            this.getList()
        },

        refreshList() {
            deletePaymentOrderNetworkCacheData();
            this.getList()
        },

        createPaymentOrder() {
            /*
            this.$router.push({
               // path: '/fund/dealingPayment/paymentorder',
                path: '/fund/fundorder/paymentorder',
            })
                */
               uiNavigation.showPaymentOrderDetailPage(this.$router)
        },

        showDetail(row) {
            /*
            this.$router.push({
                //path: '/fund/dealingPayment/paymentorder',
                 path: '/fund/fundorder/paymentorder',
                query: {
                    id: row.id
                }
            })
                */
               uiNavigation.showPaymentOrderDetailPage(this.$router, { id: row.id })
        },

        handleRowClick(row) {
            this.showDetail(row)
        },

        async reviewPaymentOrder(row) {
            try {
                await ElMessageBox.confirm(
                    `确定要审核单据【${row.docCode}】吗?`,
                    '审核确认',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                )

                const res = await this.fundUiAction.reviewPaymentOrder({
                    idList: [row.id]
                })

                if (res?.data != null) {
                    ElMessage.success('审核成功')
                    this.getList()
                } else if (res?.resErr) {
                    ElMessage.error('审核失败: ' + res.resErr)
                }
            } catch (error) {
                if (error !== 'cancel') {
                    ElMessage.error('审核操作失败')
                }
            }
        },

        formatDate(dateStr) {
            if (!dateStr) return ''
            return DateUtil.getDayTitle(dateStr)
        },

        formatCurrency(value) {
            return Util.getFundString(value)
        }
    }
}
</script>

<style scoped>
.payment-order-container {
    padding-top: 0px;
    padding-left: 20px;
}
</style>